#include <xp/bas/sio.h>
#include <xp/bas/stdio.h>
#include <xp/bas/locale.h>
#include <xp/bas/errno.h>

int xp_main (int argc, xp_char_t* argv[])
{
	xp_sio_t sio;
	xp_char_t c;
	xp_size_t err = 0;
	
	if (argc != 2) {
		xp_sio_putsn (xp_sio_err, XP_TEXT("usage: "), 
			argv[0], XP_TEXT(" file\n"), XP_NULL);
		return -1;
	}

	if (xp_setlocale () == -1) {
		xp_sio_puts (xp_sio_err, XP_TEXT("cannot set locale\n"));
		return -1;
	}

	if (xp_sio_open (&sio, argv[1], XP_TEXT("r")) == XP_NULL) {
		xp_sio_putsn (xp_sio_err, XP_TEXT("cannot open ["), 
			argv[1], XP_TEXT("]\n"), XP_NULL);
		return -1;
	}

	for (;;) {
		xp_ssize_t n = xp_sio_getc (&sio, &c);
		if (n == 0) break;

		if (n == -1) {
			if (xp_errno != XP_EILSEQ) {
				break;
			}

			err++;
			if (err > 10) break;
			continue;
		}

		xp_sio_putc (xp_sio_out, c);
	}

	if (err > 0) {
		xp_char_t buf[100];
		xp_sprintf (buf, xp_countof(buf), 
			XP_TEXT("=== %d sequence error(s) ===\n"), err);
		xp_sio_puts (xp_sio_err, buf);
		return -1;
	}

	xp_sio_rewind (&sio);
	xp_sio_puts (xp_sio_err, XP_TEXT("<<<----- after rewind ----->>>\n"));

	for (;;) {
		xp_ssize_t n = xp_sio_getc (&sio, &c);
		if (n == 0) break;

		if (n == -1) {
			if (xp_errno != XP_EILSEQ) break;

			err++;
			if (err > 10) break;
			continue;
		}

		xp_sio_putc (xp_sio_out, c);
	}

	if (err > 0) {
		xp_char_t buf[100];
		xp_sprintf (buf, xp_countof(buf), 
			XP_TEXT("=== %d sequence error(s) ===\n"), err);
		xp_sio_puts (xp_sio_err, buf);
	}

	xp_sio_close (&sio);	
	return 0;
}
